package chap6.fileio;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;

//Developed by M.Aasim
//This program searches the string "strFind" 
//in all the files having the extension "fileType"
//in "rootFolderToSearch"(and in all its subfolders) 
//and replaces that string with "strReplaceWith"


public class ChecKInFilesAndFolder {

	/**
	 * @param args
	 */
	//Change the following 4 variables according to ur requirement. 
	static String rootFolderToSearch = "D:/test";

	static String fileType = ".java";

	//static String strFind = "<%@ page language=\"java\" pageEncoding=\"UTF-8\"%>";
	
	//static String strFind = "<%@ page language =\"java\"%>";
	//static String strFind = "<%@ page language=\"java\" import=\"java.util.HashMap\"%>";	
	
	//static String strFind = "<%@ page language =\"java\" import = \"java.util.*;\"%>";
	
	//static String strFind = "<%@ page language=\"java\"  %>";
	//static String strFind = "CustomError.jsp";
	//static String strFind = "<%@ page language=\"java\" import=\"java.util.HashMap\" %>";
	//static String strReplaceWith = "<%@ page errorPage=\"/CustomError.jsp\" language=\"java\" pageEncoding=\"UTF-8\"%>";
	//static String strReplaceWith = "<%@ page errorPage=\"/CustomError.jsp\" language=\"java\" import = \"java.util.*;\"%>";
	//static String strReplaceWith = "<%@ page errorPage=\"/CustomError.jsp\" language=\"java\" import=\"java.util.HashMap\" %>";
	//static String strFind = "extends BaseDispatchAction";
	static String strFind = "catch (ProcessException e)";
	public static void main(String[] arg) {

		File directory = new File(rootFolderToSearch);
		System.out.println("Here you go...");
		visitAllDirs(directory);
		System.out.println("Done!");

	}

	public static void process(File dir) {
		String listFilenames = "";

		try { // read one text file
			String filename[] = dir.list();
			for (int i = 0; i < filename.length; i++) {
				listFilenames = filename[i];
				if (listFilenames.contains(fileType)
						&& !listFilenames.contains(".svn")) {
				boolean file_name = check(dir.getAbsolutePath() + "\\" + listFilenames);
				//if(file_name)
				//System.out.println("String Customerror present in "+dir.getAbsolutePath() + "\\" + listFilenames);
				if(file_name)
					System.out.println("String Customerror not present in "+dir.getAbsolutePath() + "\\" + listFilenames);	
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	// Process only directories under dir
	public static void visitAllDirs(File dir) {
		if (dir.isDirectory()) {

			// You can do whatever you want with this directory
			// E.g. printing its name to the console
			// System.out.println("\nDirectory name# "+dir);
			process(dir);

			String[] children = dir.list();
			for (int i = 0; i < children.length; i++) {
				visitAllDirs(new File(dir, children[i]));

				// break here if you want to stop after iterating in the first
				// directory (for testing)
				// break;
			}

		}
	}
	
	public static boolean  check(String filename)
	{
		StringBuffer str = new StringBuffer();
		@SuppressWarnings("unused")
		int i = 0;
		@SuppressWarnings("unused")
		int counter = 0;
	    
	    try {
	      //use buffering, reading one line at a time
	      //FileReader always assumes default encoding is OK!
	      BufferedReader input =  new BufferedReader(new FileReader(filename));
	      try {
	        String line = null; 
	        //int  index=0;
	        //not declared within while loop
	        /*
	        * readLine is a bit quirky :
	        * it returns the content of a line MINUS the newline.
	        * it returns null only for the END of the stream.
	        * it returns an empty String if two newlines appear in a row.
	        */
	        while (( line = input.readLine()) != null){
	        	
	        	str.append(line);
	        	i = str.length();
	        	
	        	/*
	        	 if((index = str.indexOf(strFind,index))!=-1){
	        	 }
	        	 */
	        	if(line.contains(strFind))
	        	{ while(input.readLine().contains( "conn = null")) {
	        		while(input.readLine().contains( "}")) {
	        			System.out.println("hehehe");
		        	}
	        	}
	        		
	        	}
	        	
	        }

	        
	        
	        if(str.toString().contains(strFind))
		        	{
			        	System.out.println("hehe");
			        	
			        	return true;
		        	}
	        
	        }
		catch (Exception e) {
			e.printStackTrace();
		}
	    }
		catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}
	/*public static void appendData(String filename) {
		filename = filename.replaceAll("\\\\", "/");
		System.out.println("\nProcessing file: " + filename);
		File file = new File(filename);
		FileInputStream fis = null;
		BufferedInputStream bis = null;
		DataInputStream dis = null;
		

		try {
			fis = new FileInputStream(file);

			// Here BufferedInputStream is added for fast reading.
			bis = new BufferedInputStream(fis);
			dis = new DataInputStream(bis);

			// dis.available() returns 0 if the file does not have more lines.
			StringBuffer line = new StringBuffer("");
			StringBuffer oldtext = new StringBuffer("");
			StringBuffer separator = new StringBuffer("\r\n");
			while (dis.available() != 0) {

				// this statement reads the line from the file
				// Again StringBuffer used for better performance
				if ((line = new StringBuffer(dis.readLine())) != null)
					oldtext = oldtext.append(line).append(separator);
			}

			String newtext = oldtext.toString().replaceAll(strFind,
					strReplaceWith);
			// System.out.println("\n###old text: " + oldtext);
			// System.out.println("\n###new text: " + newtext);
			
			FileWriter writer = new FileWriter(filename);
			writer.write(newtext);
			writer.close();
			
			if(!(oldtext.equals(newtext))){
			int count1 = 0;
			count1++;
			System.out.println(filename+" changed. . . "+count1);
			}
			// dispose all the resources after using them.
			fis.close();
			bis.close();
			dis.close();

		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}*/
}

